<template>
  <el-dialog draggable
    class="base-dialog-root"
    :model-value="visible"
    width="800"
    title="活动发布"
    @close="onClose"
  >
  <div class="publish-result-page">
    <div class="right">
      <template v-if="curStatus !== '1'">
        <!-- <div class="preview-container">
          <iframe :src="mainChannel.fullUrl"></iframe>
        </div> -->
        <div class="question-config" v-if="setting">
          <div class="question-config-wrapper">
            <div class="question-config-main">
              <div v-for="form of setterList" :key="form.key" class="config-item">
                <!-- <div class="config-title">
                  <span>
                    {{ form.title }}
                  </span>
                </div> -->
                <el-form
                  class="question-config-form"
                  label-position="left"
                  label-width="200px"
                  @submit.prevent
                >
                  <template v-for="(item, index) in form.formList">
                    <FormItem
                      v-if="item.type && !item.hidden && Boolean(registerTypes[item.type])"
                      :key="index"
                      :form-config="item"
                      :style="item.style"
                    >
                      <Component
                        v-if="Boolean(registerTypes[item.type])"
                        :is="components[item.type]"
                        :module-config="form.dataConfig"
                        :formId="formId"
                        :form-config="item"
                        @form-change="handleFormChange"
                      />
                    </FormItem>
                  </template>
                </el-form>
              </div>
            </div>
          </div>
        </div>
        <!-- 二维码 -->
        <div class="container-content">
          <span class="launch-tip"
            >说明：若您的活动投放对象，涉及14周岁以下的用户，需征得其监护人的同意。</span
          >
          <h2>活动链接</h2>
          <div class="main-channel-wrap">
            <ChannelRow
              :disable-delete="true"
              :data="mainChannel"
              :style-wrap="{ marginBottom: '8px' }"
            />
          </div>
        </div>
        <div class="container-content" v-if="!setting">
          <h2>查看结果</h2>
          <div class="main-channel-wrap">
            <ChannelRow
              :disable-delete="true"
              :data="resultChannel"
              :style-wrap="{ marginBottom: '8px' }"
            />
          </div>
        </div>
      </template>
      <EmptyIndex v-else :data="defaultConfig" />
    </div>
  </div>
  <template #footer>
  
  </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { computed, watch, ref, onMounted, shallowRef } from 'vue'
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
import { cloneDeep as _cloneDeep, isArray as _isArray, get as _get } from 'lodash-es'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/src/message.scss'

import baseConfig from './config/baseConfig'
import baseFormConfig from './config/baseFormConfig'
import FormItem from '@/materials/setters/widgets/FormItem.vue'
import setterLoader from '@/materials/setters/setterLoader'

import EmptyIndex from '@/management/components/EmptyIndex.vue'
import ChannelRow from './components/ChannelRow.vue'

const emit = defineEmits(['on-close-codify'])
const props = withDefaults(
  defineProps<{
    formId: string
    visible: boolean,
    setting?: boolean
  }>(),
  {
    formId: '',
    visible: false,
    setting: false
  }
)

const formConfigList = ref<Array<any>>([])
const components = shallowRef<any>({})
const registerTypes = ref<any>({})
const setterList = computed(() => {
  const list = _cloneDeep(formConfigList.value)

  return list.map((form) => {
    const dataConfig: any = {}

    for (const formItem of form.formList) {
      const formKey = formItem.key ? formItem.key : formItem.keys
      let formValue
      if (_isArray(formKey)) {
        formValue = []
        for (const key of formKey) {
          const val = _get(store.state.editform.schema, key, formItem.value)
          formValue.push(val)
          dataConfig[key] = val
        }
      } else {
        formValue = _get(store.state.editform.schema, formKey, formItem.value)
        dataConfig[formKey] = formValue
      }
      formItem.value = formValue
    }

    form.dataConfig = dataConfig

    return form
  })
})

const store = useStore()

const handleFormChange = (data: any) => {
  store.dispatch('editform/changeSchema', {
    key: data.key,
    value: data.value
  })
}

const onClose = () => {
  emit('on-close-codify')
}
// const backgroundImage = '/imgs/phone-bg.webp'
const defaultConfig = {
  title: '活动未发布',
  desc: '点击发布后，活动就可以对外投放了哦！',
  img: '/myactivity/imgs/icons/unpublished.webp'
}

const routerMode = ref(import.meta.env.VITE_ROUTER_MODE);

const metaData = computed(() => _get(store.state, 'publishform.schema.metaData'))
const curStatus = computed(() => _get(metaData.value, 'status', '1'))
const mainChannel = computed(() => {
  let fullUrl = ''

  if (metaData.value) {
    fullUrl = `${(window as any).$app?.homePage||(location.origin+'/myactivity')}/render/${metaData.value.surveyPath}?t=${Date.now()}`
    if (routerMode.value === 'hash') {
      fullUrl = `${(window as any).$app?.homePage||(location.origin+'/myactivity')}/render.html#/${metaData.value.surveyPath}?t=${Date.now()}`
    }
  }
console.log('fullUrl', fullUrl)
  return { fullUrl }
})
const resultChannel = computed(() => {
  let fullUrl = ''

  if (metaData.value) {
    fullUrl = `${(window as any).$app?.homePage||(location.origin+'/myactivity')}/analysis/${metaData.value.surveyPath}?t=${Date.now()}`
    if (routerMode.value === 'hash') {
      fullUrl = `${(window as any).$app?.homePage||(location.origin+'/myactivity')}/render.html#/${metaData.value.surveyPath}?t=${Date.now()}`
    }
  }
console.log('fullUrl', fullUrl)
  return { fullUrl }
})

// const route = useRoute()
const router = useRouter()

watch(
  () => props.visible,
  async (val: boolean) => {
    if (val && props.formId) {
      store.commit('publishform/setFormId', props.formId)

      try {
        await store.dispatch('publishform/init')
      } catch (err: any) {
        ElMessage.error(err.message)
        setTimeout(() => {
          router.replace({ name: 'forms' })
        }, 1000)
      }

      if (props.setting) {
        formConfigList.value = baseConfig.map((item: any) => ({
          ...item,
          formList: item.formList.map((key: any) => (baseFormConfig as any)[key]).filter((config: any) => !!config)
        }))

        const formList = formConfigList.value.map((item) => item.formList).flat()
        const typeList = formList.map((item) => ({
          type: item.type,
          path: item.path || item.type
        }))

        const comps = await setterLoader.loadComponents(typeList)
        for (const comp of comps) {
          if (!comp) {
            continue
          }

          const { type, component, err } = comp
          if (!err) {
            const componentName = component.name

            components.value[type] = component
            registerTypes.value[type] = componentName
          }
        }
      }
    }
  }
)
</script>
<style lang="scss" scoped>
.publish-result-page {
  width: 100%;
  height: 100%;
  overflow: hidden;

  .left {
    position: fixed;
    left: 0;
    top: 0;
    z-index: 100;
  }

  .right {
    width: 100%;
    height: 100%;
    overflow: hidden;
    // padding-left: 80px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    // background: #f6f7f9;
    // padding: 30px 40px 50px 40px;
  }

  .question-config {
    width: 100%;
    padding: 10px 20px;
    // border-top: 4px solid #f1f2f3;
    border-bottom: 4px solid #f1f2f3;
  }
  .preview-container {
    width: 442px;
    height: 810px;
    flex-grow: 0;
    flex-shrink: 0;
    overflow: hidden;
    padding: 70px 28px 26px 27px;
    background-position: 0 0;
    background-size: 100% 100%;
    background-image: url('@/assets/images/phone-bg.webp');

    iframe {
      width: 100%;
      height: 100%;
      border-radius: 0 0 50px 50px;
      border: none;
    }
  }
}

.container-content {
  margin-left: 20px;
  background-color: #fff;
  // width: 560px;
  padding: 30px 30px 80px;
  border-radius: 2px;

  .launch-tip {
    font-size: 12px;
    color: #fa881a;
  }

  h2 {
    font-family: PingFangSC-Medium;
    margin: 20px 0 0 0;
    font-size: 18px;
    color: #4a4c5b;
    letter-spacing: 0;
    line-height: 26px;
  }
}
</style>
